package com.bwie.service.impl;

import ch.qos.logback.core.joran.action.IADataForComplexProperty;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.UserResponse;
import com.bwie.common.redis.RedisCache;
import com.bwie.common.remote.system.RemoteUserService;
import com.bwie.common.result.Result;
import com.bwie.common.utils.IdUtils;
import com.bwie.common.utils.JwtUtils;
import com.bwie.service.AuthService;
import org.bouncycastle.pqc.math.linearalgebra.RandUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author：ShenJiaFeng
 * @Package：com.bwie.service.impl
 * @Project：zg6_yuekao
 * @name：AuthServiceImpl
 * @Date：2024/5/17 10:00
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Result sendCode(String phone) {
        if (phone == null||phone.isEmpty()){
            throw new IllegalArgumentException("手机号不能为空");
        }

        Result<User> result = remoteUserService.findByPhone(phone);
        User user = result.getData();
        if (!user.getPhone().equals(phone)){
            throw new IllegalArgumentException("手机号不存在");
        }
        int code = new Random().nextInt(9000);
        redisTemplate.opsForValue().set(phone,String.valueOf(code));
        return Result.success(code, "发送成功验证码是:" + code);
    }

    @Override
    public Result<UserResponse> login(String phone, String code) {
        Result<User> result = remoteUserService.findByPhone(phone);
        boolean success = result.isSuccess();
        if (!success) {
            throw new IllegalArgumentException("登录异常");
        }
        User user = result.getData();
        if (phone == null) {
            throw new IllegalArgumentException("手机号不存在");
        }
        if (code == null) {
            throw new IllegalArgumentException("验证码不存在");
        }
        //验证码redis
        String phoneCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(phoneCode)) {
            throw new IllegalArgumentException("验证码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        String userKey = IdUtils.genId();
        map.put(JwtConstants.USER_KEY, userKey);
        map.put(JwtConstants.DETAILS_USER_ID, user.getUserId());
        map.put(JwtConstants.DETAILS_USERNAME, user.getUserName());
        String token = JwtUtils.createToken(map);
        redisCache.setCacheObject(
                TokenConstants.LOGIN_TOKEN_KEY + userKey,
                user,
                TokenConstants.EXPIRATION,
                TimeUnit.MINUTES
        );
        return Result.success(
                UserResponse.builder()
                        .token(token)
                        .outTime(TokenConstants.EXPIRATION)
                        .build(),"登录成功"
        );
    }

    @Override
    public User userInfo() {
        return redisCache.getCacheObject(
                TokenConstants.LOGIN_TOKEN_KEY+request.getHeader(JwtConstants.USER_KEY)
        );
    }
}
